﻿
namespace MyFurion.Application
{
    /// <summary>
    /// 机构数据权限仓储
    /// </summary>
    public class OrgPerRepository : BaseRepository<OrgPerInfo>,ITransient
    {
        /// <summary>
        /// 授权角色机构权限
        /// </summary>
        /// <param name="roleId">角色id</param>
        /// <param name="grantOrgs">机构id</param>
        /// <returns></returns>
        public async Task GrantOrg(long roleId, List<long> grantOrgs)
        {
            List<long> oldIds = await Context.Queryable<OrgPerInfo>().Where(p => p.RoleId == roleId).Select(p => p.Id).ToListAsync();
            //插入数据
            if (grantOrgs.Any())
            {
                var orgs = grantOrgs.Select(u => new OrgPerInfo
                {
                    RoleId = roleId,
                    OrgId = u
                }).ToList();
                await Insert(orgs);
            }
            //删除原有关联机构
            if (oldIds.Any())
            {
                await DeleteByWhere(p => oldIds.Contains(p.Id), true);
            }
        }
        /// <summary>
        /// 获取角色机构权限id集合
        /// </summary>
        /// <param name="roleIds"></param>
        /// <returns></returns>
        public async Task<List<long>> GetRoleOrgIds(List<long> roleIds)
        {
            return await Context.Queryable<OrgPerInfo>().Where(it => roleIds.Contains(it.RoleId)).Select(it => it.OrgId).ToListAsync();
        }
    }
}
